import config from '../../config';
import { getUserInfo, updateUserInfo, sign } from '../../api/index';

let app = getApp();

Page({
  data: {
    imgPrefix: config.IMG_PREFIX,
    showCheckModal: false,
    showInviteModal: false,
    info: {
      chance: 0,
      score: 0,
      win_count: 0,
      win_rate: 0,
      is_sign: false
    },
    submitting: false
  },

  onLoad(options) {
    app
      .getToken()
      .then(() => {
        this.fetchUserData(options.friend_id);
      })
      .catch(err => {
        console.log(err);
      });
  },

  onShareAppMessage() {
    return {
      title: '吃鸡答题',
      path: '/pages/index/index?friend_id=' + this.data.info.id,
      imageUrl: config.IMG_PREFIX + '/images/share_thumb.jpeg'
    };
  },

  fetchUserData(friend_id) {
    let formData = {};
    if (friend_id) {
      formData.friend_id = friend_id;
    }

    if (this.data.submitting) {
      return;
    }

    this.setData({
      submitting: true
    });

    getUserInfo({
      data: formData,
      success: res => {
        const { data } = res.data;
        wx.setStorageSync(config.USER_INFO_KEY, data);
        this.setData({
          submitting: false,
          info: data
        });
      }
    });
  },

  goPost() {
    wx.navigateTo({
      url: '/pages/post/post'
    });
  },

  goRank() {
    wx.navigateTo({
      url: '/pages/rank/rank'
    });
  },

  tapSign() {
    if (this.data.submitting) {
      return;
    }

    this.setData({
      submitting: true
    });

    sign({
      success: res => {
        this.setData({
          submitting: false,
          'info.chance': res.data.data.chance,
          'info.is_sign': true
        });
        this.openCheckModal();
      }
    });
  },

  openModal(key) {
    this.setData({
      ['show' + key]: true
    });
  },

  closeModal(key) {
    this.setData({
      ['show' + key]: false
    });
  },

  openCheckModal() {
    this.openModal('CheckModal');
  },

  closeCheckModal() {
    this.closeModal('CheckModal');
  },

  openInviteModal() {
    this.openModal('InviteModal');
  },

  closeInviteModal() {
    this.closeModal('InviteModal');
  },

  onUserInfo(res) {
    if (this.data.submitting) {
      return;
    }

    if (this.data.info.chance === 0) {
      wx.showModal({
        title: '提示',
        content: '没有参与次数',
        showCancel: false
      });
      return;
    }

    let userInfo = res.detail.userInfo;
    userInfo.headimgurl = userInfo.avatarUrl;
    userInfo.nickname = userInfo.nickName;
    userInfo.sex = userInfo.gender;

    // wx.setStorageSync(config.USER_INFO_KEY, userInfo);
    this.setData({
      submitting: true
    });
    updateUserInfo({
      data: userInfo,
      success: () => {
        wx.navigateTo({
          url: '/pages/enter/enter'
        });
      }
    });
  }
});
